//
//  ModifyProfileVC.swift
//  Hyphenate-Demo-Swift
//
//  Created by cydida on 2018/12/3.
//  Copyright © 2018年 curtainups. All rights reserved.
//

import UIKit
import Hyphenate
import PGDatePicker
import Alamofire
import Photos

class ModifyProfileVC: UITableViewController {
    
    @IBOutlet weak var firstNameField: UITextField!
    @IBOutlet weak var lastNameField: UITextField!
//    @IBOutlet weak var birthdayLabel: UILabel!
    @IBOutlet weak var genderLabel: UILabel!
    @IBOutlet weak var phoneLabel: UILabel!
    @IBOutlet weak var countryField: UITextField!
    @IBOutlet weak var cityField: UITextField!
    @IBOutlet weak var avatarImgView: UIImageView!
    @IBOutlet weak var userNameLabel: UILabel!
    
    @IBOutlet weak var avatarBorderControl: UIControl!
    
    var imageLocalPath = ""


    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = EnStatic.getWord(keyWord: "Edit profile") 
        
//        self.tableView.contentInset = UIEdgeInsetsMake(-20, 0, 0, 0)
        
        avatarImgView.layer.cornerRadius = 45;
        avatarImgView.layer.masksToBounds = true;
        avatarBorderControl.layer.cornerRadius = 50
        avatarBorderControl.layer.masksToBounds = true
        
        //头像本地临时存储路径
        let rootPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,
                                                           .userDomainMask, true)[0] as String
        imageLocalPath = "\(rootPath)/selectedImage.jpg"
        
        getProfile()
    }
//    
    @IBAction func avatarAction(_ sender: Any)
    {
        let imagePickerController = UIImagePickerController()
        imagePickerController.sourceType = .photoLibrary
        imagePickerController.delegate = self
        self.present(imagePickerController, animated: true, completion: nil)
        
    }
    @IBAction func saveAction(_ sender: Any)
    {
        postProfile()
    }
    /// MARK:获取个人资料
    func getProfile()
    {
        //根据loginOwner合成urlstr
        var urlString : String = ""
        
        urlString = "profile?username=" + EMClient.shared().currentUsername
        
        let cuHTTP = CUHTTP.instance()
        
        weak var weakSelf = self
        
        cuHTTP.makeGetData(url: urlString, success: {response in
            print("Response String: \(String(describing: response?.result.value))")
            print(response?.response?.statusCode ?? "??")      //成功时，返回200
            if let value = response?.result.value {
                let data = value.data(using: String.Encoding.utf8)! as NSData
                let json = try? JSONSerialization.jsonObject(with: data as Data,
                                                             options:.allowFragments) as! [String: Any]
                print(json ?? "??")
                let allEvents = json!["user"] as Any
                print(allEvents)
                
                let loopE = allEvents as! [String: Any]
                if let tmpStr0 = loopE["username"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        weakSelf?.userNameLabel.text = tmpStr1
                    }
                }
                if let tmpStr0 = loopE["city"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        weakSelf?.cityField.text = tmpStr1
                    }
                }
                if let tmpStr0 = loopE["firstName"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        weakSelf?.firstNameField.text = tmpStr1
                    }
                }
                //                if let tmpStr0 = loopE["middleName"] {
                //                    if let tmpStr1 = (tmpStr0 as? String) {
                //                        self.middleName = tmpStr1
                //                        self.middleNameView.text = self.middleName
                //                    }
                //                }
                if let tmpStr0 = loopE["lastName"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        weakSelf?.lastNameField.text = tmpStr1
                    }
                }
                if let tmpStr0 = loopE["country"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        let tmpStr2 = EnStatic.getWord(keyWord: tmpStr1)
                        weakSelf?.countryField.text = tmpStr2
                    }
                }
//                if let tmpStr0 = loopE["dob"] {
//                    if let tmpStr1 = (tmpStr0 as? String) {
//                        weakSelf?.birthdayLabel.text = tmpStr1
//                    }
//                }
                if let tmpStr0 = loopE["gender"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        let tmpStr2 = EnStatic.getWord(keyWord: tmpStr1)
                        weakSelf?.genderLabel.text = tmpStr2
                    }
                }

                if let tmpStr0 = loopE["phone"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        weakSelf?.phoneLabel.text = tmpStr1
                    }
                }
                
                if let tmpStr0 = loopE["countryCode"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        weakSelf?.phoneLabel.text = "(+" + tmpStr1 + ")" + (weakSelf?.phoneLabel.text)!
                    }
                }
                //读取头像文件全路径
                if let tmpStr0 = loopE["imageName"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        let url = URL(string: CUHTTP.URL.ROOT + "images/" + tmpStr1)
                        //                        self.imagePath = tmpStr1
                        weakSelf?.avatarImgView.sd_setImage(with: url, placeholderImage: UIImage(named: "default_avatar"))
                    }
                }
                
            }
        },
        failure:{ response in
                print(response ?? " ")
                weakSelf?.show(EnStatic.getWord(keyWord: "get data failed"))
            }
        )
    }
    
    
    /// MARK:提交新的profile信息
    func postProfile() {
        
        let firstName = firstNameField.text ?? ""
        let lastName = lastNameField.text ?? ""
//        let birthDay = birthdayLabel.text ?? ""
        let gender = genderLabel.text ?? ""
        let city = cityField.text ?? ""
        let country = countryField.text ?? ""
        let cuHTTP = CUHTTP.instance()

        let urlString = "profile?username=" + EMClient.shared().currentUsername

        var parameters: [String: Any]

        parameters = [
            "username" : EMClient.shared().currentUsername,
            "city" : city,
            "firstName" : firstName,
//            "middleName" : middleName,
            "lastName" : lastName,
            "country" : country,
//            "dob" : birthDay,
            "gender" : gender
//            "imageName" : imagePath
        ]

        print("parameters12 = ",parameters)
        
        weak var weakSelf = self

        cuHTTP.makePostData(url: urlString, parameters: parameters,
                            success: {response in
                                print(response?.response?.statusCode ?? "??")      //成功时，返回200
                                self.navigationController?.popViewController(animated: true)
        } ,
        failure: {response in
                weakSelf?.show(EnStatic.getWord(keyWord: "save failed"))
            }
        )
        
    }
    


    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        switch indexPath.row {
//            case 2:
//                birthDayAction()
            case 2:
                sexAction()
//            case 4:
            default:
                break;
        }
    }
    
//    private func birthDayAction (){
//        
//        let datePickerManager = PGDatePickManager()
//        let datePicker = datePickerManager.datePicker!
//        datePicker.delegate = self
//        datePicker.isHiddenMiddleText = false;
//        datePicker.datePickerType = .type2;
//        datePicker.datePickerMode = .date
////        datePicker.minimumDate = Date()
//        self.present(datePickerManager, animated: false, completion: nil)
//    }
    
    private func sexAction () {
        
        weak var weakSelf = self
        let alert = UIAlertController(title:"",message:"gender".localized(),preferredStyle:UIAlertControllerStyle.actionSheet)
        let male = UIAlertAction(title:EnStatic.getWord(keyWord: "male"),style:UIAlertActionStyle.default,handler:{(alerts:UIAlertAction) -> Void in
            weakSelf?.genderLabel.text = EnStatic.getWord(keyWord: "male");
        })
        let female  = UIAlertAction(title:EnStatic.getWord(keyWord: "female"),style:UIAlertActionStyle.default,handler:{(alerts:UIAlertAction) -> Void in
            weakSelf?.genderLabel.text = EnStatic.getWord(keyWord: "female");
        })
        let cancel = UIAlertAction(title:"Cancel".localized(),style:UIAlertActionStyle.cancel,handler:nil)
        alert.addAction(male)
        alert.addAction(female)
        alert.addAction(cancel)
        self.present(alert,animated: true,completion: nil)
    }
    
//    //上传图片
    func uploadImage() {
            let image =  UIImage(contentsOfFile: imageLocalPath)
            let imgData = UIImageJPEGRepresentation(image!, 0.2)!
            let parameters = ["username": EMClient.shared().currentUsername,"lang":Locale.current.languageCode]
            Alamofire.upload(multipartFormData: { (multipartFormData) in
                multipartFormData.append(imgData, withName: "image", fileName: "user_profiel_image.jpeg", mimeType: "image/jpeg")
                for (key, value) in parameters {
                    multipartFormData.append((value?.data(using: String.Encoding.utf8))!, withName: key)
                }
            }, to: CUHTTP.URL.ROOT + "profileImage/")
            { (result) in
                switch result {
                case .success(let upload, _, _):

                    upload.uploadProgress(closure: { (progress) in
                        //Print progress
                    })

                    upload.responseString { response in
                        print(response.result)
                        print(response.response?.statusCode)      //成功时，返回200
                        
                        guard let code = response.response?.statusCode else{
                            return;
                        }
                        
                        if(code == 201 || code == 200)
                        {
                            if response.result.isSuccess {
                                print(response.response?.allHeaderFields ?? " ")
                                let data = response.response! as HTTPURLResponse
                                let field = data.allHeaderFields["Location"] as! String
                                
                                let defaults = UserDefaults.standard
                                defaults.set(CUHTTP.URL.ROOT + "/"+field, forKey: EMClient.shared().currentUsername+"_avatar")
                                defaults.synchronize()
                            }
                        }
                        

                    }

                case .failure(let encodingError): break
                }
            }
    }
}



/// MARK:PGDatePickerDelegate
//extension ModifyProfileVC : PGDatePickerDelegate {
//
//    func datePicker(_ datePicker: PGDatePicker!, didSelectDate dateComponents: DateComponents!) {
//        print("dateComponents = ", dateComponents)
//
//        guard let dateComponents = dateComponents,
//            let year = dateComponents.year,
//            let month = dateComponents.month,
//            let day = dateComponents.day else{
//
//                return;
//        }
//        let monthStr = String(format: "%02d", month)
//        let dayStr = String(format: "%02d", day)
//
//        birthdayLabel.text = "\(String(describing: year))"  + "-" + monthStr  + "-" + dayStr
//
//    }
//}

/// MARK:UIImagePickerControllerDelegate
extension ModifyProfileVC: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        
        // Dismiss the picker if the user canceled.
        dismiss(animated: true, completion: nil)
        
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        // The info dictionary may contain multiple representations of the image. You want to use the original.
        guard var selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }
        
        // Dismiss the picker.
        dismiss(animated: true, completion: nil)
        
        //压缩图片到36k左右
        let img = selectedImage.imageByScalingAndCroppingForSize(targetSize: CGSize.init(width: 160, height: 160))
        selectedImage = img
        
        var KB = 0.0
        if let imageData = UIImagePNGRepresentation(selectedImage) {
            let bytes = imageData.count
            KB = Double(bytes) / (1024.0*1024.0) // Note the difference
        }
        //2M
        if KB >= 2 {
            //图片太大
            self.show(EnStatic.getWord(keyWord: "avatar bigger than 2M"))
            //设置无头像状态
        } else {
            // Set photoImageView to display the selected image.
            self.avatarImgView.image = selectedImage
            
            //将选择的图片保存到Document目录下
            let fileManager = FileManager.default
            let imageData = UIImageJPEGRepresentation(selectedImage, 1.0)
            fileManager.createFile(atPath: imageLocalPath, contents: imageData, attributes: nil)
            
            self.uploadImage()
        }
        
    }
}
